from contextlib import closing
from os import makedirs
from os.path import exists

import requests


def download(photo_url, dir_name, filename):
    jpg_filename = dir_name + '/' + filename
    if not exists(jpg_filename):
        with closing(requests.get(url=photo_url, stream=True, timeout=90)) as r:
            with open(jpg_filename, 'ab+') as f:
                for chunk in r.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(chunk)
                        f.flush()


def post_yinghuo():
    # last_id=0&system_version=6.0.1&lan=en&source=android&token=6ef3a7e96128db97d3e67c6adeac62f9&uuid=1d4e879a-6fbc-3049-78e9-2189b72c6b64&version_code=2019120900&timestamp=1578637025&device_code=&device_name=SAMSUNG-SM-G925A&udid=ee2f71475b1647ec&page=1&channel=c1098&nonce=1578637025966E0

    feature = 1
    page = 1
    pre_ = "c_"
    if not exists("video"):
        makedirs("video")
    if not exists("images"):
        makedirs("images")
    while True:
        try:
            payload = {'last_id': '0', 'system_version': '6.0.1', 'lan': 'en', 'source': 'android',
                       'token': '91666eb5d4cdb145b57d7b23890e5a5d', 'uuid': '1d4e879a-6fbc-3049-78e9-2189b72c6b64',
                       'version_code': '2020092502', 'timestamp': '1603260535', 'device_code': '',
                       'device_name': 'SAMSUNG-SM-G925A', 'udid': 'ee2f71475b1647ec', 'page': page, 'channel': 'c1098',
                       'nonce': '160326053564757'}
            r = requests.post("https://api.hyhuo.com/home/list", data=payload)
            print(page)
            # print(r.json())
            page = page + 1
            json_data = r.json()
            data = json_data['data']
            if data:
                data_list = data['data_list']
                if data_list:
                    for item in data_list:
                        try:
                            print(item)
                            thumb_img = item['thumb_img']
                            download(thumb_img, "video", pre_ + str(feature) + ".jpg")
                            video_url_hd = item['video_url_hd']
                            download(video_url_hd, "video", pre_ + str(feature) + ".mp4")
                            print("已保存视频: " + pre_ + str(feature) + ".mp4")
                            feature = feature + 1
                        except:
                            pass
                else:
                    print("在第" + str(page) + "页因各种原因退出， feature 已经到达:" + str(feature))
                    break
            else:
                print("在第" + str(page) + "页因各种原因退出， feature 已经到达:" + str(feature))
                break
        except:
            print("在第" + str(page) + "页因各种原因退出， feature 已经到达:" + str(feature))
            pass


if __name__ == '__main__':
    post_yinghuo()
